package com.seata.simples.common.config;

import com.seata.simples.common.interceptor.SeataRestTemplateInterceptor;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/11/6 13:29
 * @description
 * @Modify By：
 * @ModifyTime： 2019/11/6
 * @Modify marker：
 **/
@Configuration
@NoArgsConstructor
public class SeataRestTemplateAutoConfiguration {
    @Autowired(
            required = false
    )
    private Collection<RestTemplate> restTemplates;
    @Autowired
    private SeataRestTemplateInterceptor seataRestTemplateInterceptor;

    @Bean
    public SeataRestTemplateInterceptor seataRestTemplateInterceptor(){
        return new SeataRestTemplateInterceptor();
    }
    //注释用于在依赖关系注入完成之后需要执行的方法上
    @PostConstruct
    public void init(){
        if(this.restTemplates!=null){
            Iterator var1= this.restTemplates.iterator();
            while (var1.hasNext()){
                RestTemplate restTemplate=(RestTemplate)var1.next();
                List<ClientHttpRequestInterceptor> interceptorList= new ArrayList(restTemplate.getInterceptors());
                interceptorList.add(this.seataRestTemplateInterceptor);
                restTemplate.setInterceptors(interceptorList);
            }
        }
    }


}
